<?php

namespace app\common;
use Firebase\JWT\JWT;
use Firebase\JWT\JWK;
use Firebase\JWT\Key;
class JwtAuth
{
    private string $key = '1421931721'; // 应该是一个复杂的密钥
    private string $issuer = 'mengxianpu'; // 发行者
    private string $audience = 'mengxianpu'; // 接收者
    private string $algorithm = 'HS256'; // 加密算法

    public function createToken($user_id): string
    {
        $iat = time(); // 当前时间
        $nbf = $iat + 10; // 在10秒内无法使用
        $exp = $iat + 3600; // 过期时间为1小时

        $payload = [
            'iss' => $this->issuer,
            'aud' => $this->audience,
            'iat' => $iat,
            'nbf' => $nbf,
            'exp' => $exp,
            'data' => [
                'user_id' => $user_id
            ]
        ];
//        return JWT::encode($payload, new Key($this->key, 'HS256'));
        return JWT::encode($payload,$this->key ,'HS256');
    }

    public function authenticateToken($token): bool|array
    {
        try {
            $decoded = JWT::decode($token, new Key($this->key, $this->algorithm));
            return (array) $decoded->data;
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * 进行token校验
     * @return array|bool
     */
    public function checkToken(): array|bool
    {
        $token = request()->header('Authorization'); // 从HTTP头信息中获取Token
        $userData = $this->authenticateToken($token);
        if ($userData) {
            return ['user' => $userData];
        } else {
            return false;
        }
    }

}